package com.shensi.appCollect.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/***
 * 替换spring默认线程池
 * 全局统一使用此线程池
 *
 * @Author joeley
 * @Date 2023-01-10
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    private static final int CPU_NUM = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_NUM + 1;
    private static final int MAX_POOL_SIZE = 2 * CPU_NUM + 1;

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //设置线程池参数信息
        //核心线程池大小
        taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        //最大线程数
        taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        //配置队列容量，默认值为Integer.MAX_VALUE
        taskExecutor.setQueueCapacity(50);
        //活跃时间 当线程空闲时间达到keepAliveTime时，线程会退出，直到线程数量=corePoolSize

        taskExecutor.setKeepAliveSeconds(60);
        //如果allowCoreThreadTimeout=true，则会直到线程数量=0
        //taskExecutor.setAllowCoreThreadTimeOut(true);
        //线程名字前缀
        taskExecutor.setThreadNamePrefix("joe-");
        //等待所有的任务结束后再关闭线程池
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        //设置此执行程序应该在关闭时阻止的最大秒数，以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
        taskExecutor.setAwaitTerminationSeconds(60);
        //修改拒绝策略为使用当前线程执行
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化线程池
        taskExecutor.initialize();
        return taskExecutor;
    }

//    @Bean("poolExecutor")
//    public Executor poolExecutor() {
//        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//        //设置线程池参数信息
//        taskExecutor.setCorePoolSize(10);
//        taskExecutor.setMaxPoolSize(50);
//        taskExecutor.setQueueCapacity(200);
//        taskExecutor.setKeepAliveSeconds(60);
//        taskExecutor.setThreadNamePrefix("myExecutor2--");
//        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
//        taskExecutor.setAwaitTerminationSeconds(60);
//        //修改拒绝策略为使用当前线程执行
//        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        //初始化线程池
//        taskExecutor.initialize();
//        return taskExecutor;
//    }

}